<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 资源位类
 * @package  module
 * @author   allen.qiang
 * @version 1.0
 */

class source {

    /**
     * 查询前端资源
     * @param array $arg_array 查询参数数组
     * @return array|null
     */
    public function searchSource( $arg_array ) {

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //分类ID
        if (isset($arg_array['source_id']) && quanli_is_int($arg_array['source_id'])) {
            $sql .= ' AND source_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['source_id'];
        }

        //页面类型
        if (isset($arg_array['page_type']) && quanli_is_int($arg_array['page_type'])) {
            $sql .= ' AND page_type = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['page_type'];
        }

        //城市ID
        if (isset($arg_array['cityID']) && quanli_is_int($arg_array['cityID'])) {
            $sql .= ' AND cityID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['cityID'];
        }

        //扩展
        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }


        //排序
        if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
            $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

        //查询分类信息
        $search_sql = 'SELECT * FROM content_source ' . $sql;

        $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
        if (!$temp_item_array)
            return null;

        $item_array = array();

        //判断上下架和销售状态
        foreach($temp_item_array as &$item) {

            //MK-FUN-1018-MCAKE-商品售罄功能 add by allen.qiang 2015-05-11 Start

            if(!is_null($item->postID)){

                //先查mainPostID 再统计销售状态
                $mainRow = $G_SHOP->DBCA->stmt_query('SELECT mainPostID FROM goods_sale WHERE postID = '.$item->postID);
            }
//            error_log(print_r(11111111,1));
//            error_log(print_r($mainRow,1));
//            error_log(print_r(22222222,1));
            //判断是否是商品
            if(  isset($mainRow) && $mainRow){

                $mainPostID = $mainRow[0]->mainPostID;

                //查询上架商品 统计数量和网站状态 useFlg 0 1 2 分别代表 下架 上架 和 售罄
                $result = $G_SHOP->DBCA->stmt_query('SELECT COUNT(uuid) AS num, SUM(useFlg) AS useFlg FROM goods_sale WHERE useFlg !=0 AND mainPostID='.$mainPostID);

                $row = $result[0];

                //判断销售状态 如果统计的网站状态等于数量*2 说明全部售罄
                $sale_status = ($row->useFlg==$row->num*2)?0:1;

            }else{
                $sale_status = 1;
            }



            //MK-FUN-1018-MCAKE-商品售罄功能 add by allen.qiang 2015-05-11 End



            $item_array[] = array(
                'source_id' => $item->source_id,
                'source_title' => $item->source_title,
                'img_link' => $item->img_link ? G_IMAGE_URL . $item->img_link : '',
                'url_link' => $item->url_link ? $item->url_link : '',
                'description' => $item->description,
                'postID' => $item->postID,
                'sort' => $item->sort,
                'page_type' => $item->page_type,
                'module' => $item->module,
                'cityID' => $item->cityID,
                'mainPostID' => isset($mainPostID) ? $mainPostID : 0,   //108-MK-AC-1015-MCAKE-BD儿童节活动 add by guojun.song 2015-05-20 
                'sale_status' => $sale_status //MK-FUN-1018-MCAKE-商品售罄功能 add by allen.qiang 2015-05-11
            );

        }

        return $item_array;

    }

    public function searchShopSource( $page_type, $cityID, $page_source = 'pc', $get_tag = 'all') {

        global $G_SHOP;

        if (!isset($page_type, $cityID) || !quanli_is_int($page_type) || !quanli_is_int($cityID)) {
            return null;
        }

        //查询资源位
        $args_array = array(
            'page_type' => $page_type,
            'cityID' => $cityID,
            'sortname' => 'sort',
            'sortorder' => 'ASC',
        );

        //tag筛选判断
        $check_tag = ($get_tag != 'all') ? true : false;

        $source_array = $this->searchSource( $args_array );
        if (!$source_array) {
            return null;
        }

        //加载类文件
        quanli_include('module/base/goods/quanliGoods.class.php');
        quanli_include('module/base/goods/goodsBasic.class.php');
        quanli_include('module/base/goods/goodsTag.class.php');

        //实例商品类
        $quanliGoods = new quanliGoods( $G_SHOP->DBCA );

        //实例商品基础信息类
        $goodsBasic = new goodsBasic( $G_SHOP->DBCA );

        //实例商品标签类
        $goodsTag = new goodsTag( $G_SHOP->DBCA );

        //组装前端资源数组
        $shop_source_array = array();

        foreach($source_array as &$source) {

            $module = &$source['module']; //模块

            switch( $module ) {

                case 'product':
                case 'product_wap':

                    //检查商品信息
                    $goods_args_array = array (
                        'cityID' => $cityID,
                        'postID' => $source['postID']
                    );
                    $goods_array = $quanliGoods->searchGoodsSaleDetail( $goods_args_array );
                    if (!$goods_array) {
                        continue;
                    }

                    //查询甜度
                    $arg_array = array(
                        'postID' => $goods_array['twoPostID'],
                        'basicGroupID' => 3
                    );
                    $goods_basic_array = $goodsBasic->searchBasicRelation( $arg_array );

                    $source['img_link'] = $goods_array['img_link'];
                    if ($page_source == 'pc') {
                        $source['url_link'] = $goods_array['link'];
                    } else {
                        $source['url_link'] = $goods_array['wap_link'];
                    }
                    $source['twoPostID'] = $goods_array['twoPostID'];
                    $source['price'] = $goods_array['salePrice'];
                    $source['frenchName'] = $goods_array['frenchName'];
                    $source['spec'] = $goods_array['spec'];
                    $source['tag_img_link'] = $goods_array['tag_img_link'];
                    $source['basicName'] = $goods_basic_array ? $goods_basic_array[0]['basicName'] : 1;
                    $source['tag'] = '';
                    $source['tagName'] = '';

                    //查询商品标签
                    $arg_array = array(
                        'postID' => $goods_array['twoPostID']
                    );
                    $goods_tag = $goodsTag->searchTagRelation( $arg_array );

                    if ($goods_tag) {
                        $source['tag'] = array();
                        $i = 0;
                        foreach($goods_tag as &$goods_tag) {
                            $source['tag'][] = $goods_tag['memoName'];

                            if($check_tag && $goods_tag['tagName'] == $get_tag){//判断商品是否有tag
                                $i++;
                            }
                        }
                        $source['tag'] = implode(' ', $source['tag']);
                    }
                    break;

                default:
                    break;
            }

            if(!$check_tag){//tag过滤判断
                $shop_source_array[$module][] = $source;
            }elseif($check_tag && $i>0){
                $shop_source_array[$module][] = $source;
            }
        }
        return $shop_source_array;
    }

    /**
     * 保存前端资源
     * @param array $args_array 资源数组
     * @return array
     */
    public function editSource( $args_array ) {

        global $G_SHOP;

        //参数检查
        if (!isset($args_array['page_type'], $args_array['cityID'], $args_array['source_data'], $args_array['operator']) || empty($args_array['operator'])) {
            return array( 'code' => 400, 'message' => '参数错误');
        }

        if (!in_array($args_array['page_type'], array(1, 2)) || !quanli_is_int($args_array['cityID']) || !is_array($args_array['source_data'])) {
            return array( 'code' => 400, 'message' => '参数错误');
        }

        //加载类文件
        quanli_include('module/base/goods/quanliGoods.class.php');
        quanli_include('module/base/system/sysRegion.class.php');
        quanli_include('module/base/common/quanliFile.class.php');

        //实例商品类
        $quanliGoods = new quanliGoods( $G_SHOP->DBCA );

        //实例地址类
        $sysRegion = new sysRegion( $G_SHOP->DBCA );

        //实例文件类
        $quanliFile = new quanliFile();

        try {

            $G_SHOP->DBCA->beginTransaction();

            //检查地址信息
            $region_args_array = array(
                'id' => $args_array['cityID'],
                'region_level' => G_CITY_LEVEL
            );
            $region_array = $sysRegion->getAreaManageList( $region_args_array );
            if (!$region_array) {
                throw new Exception('城市信息没有找到', 404);
            }

            //删除已有的资源
            $G_SHOP->DBCA->stmt_query('DELETE FROM content_source WHERE page_type = ? AND cityID = ?', 'ii',
                                       $args_array['page_type'], $args_array['cityID']);

            foreach($args_array['source_data'] as $module_name => &$module_array) {

                if (!is_array($module_array) || empty($module_array)) {
                    throw new Exception('模块没有内容', 404);
                }

                $module_item_amount = 0;

                foreach($module_array as $key => &$source) {

                    //检查标题
                    if (!isset($source['source_title']) || empty($source['source_title'])) {
                        continue;
                    }

                    //保存资源信息
                    $content_source = new entity('content_source');
                    $content_source->creator = $args_array['operator'];
                    $content_source->source_title = $source['source_title'];

                    //根据模板进行判断页面传值
                    switch( $module_name ) {

                        case 'product': //商品
                        case 'product_wap': //商品

                            if (!isset($source['postID']) || !quanli_is_int($source['postID'])) {
                                continue;
                            }

                            //检查商品信息
                            $goods_args_array = array(
                                'postID' => $source['postID']
                            );
                            $goods_array = $quanliGoods->searchGoodsSaleDetail( $goods_args_array );
                            if (!$goods_array) {
                                continue;
                            }

                            $content_source->postID = $source['postID'];

                            break;
                        case 'flash':
                        case 'flash_wap':

                            if (!isset($source['url_link']) || empty($source['url_link'])) {
                                continue;
                            }

                            if (!isset($source['img_link']) || empty($source['img_link'])) {
                                continue;
                            }

                            $content_source->img_link = $quanliFile->basename_db( $source['img_link'] );
                            $content_source->url_link = $source['url_link'];

                            break;
                        case 'html':

                            if (!isset($source['description']) || empty($source['description'])) {
                                continue;
                            }
                            $content_source->description = $source['description'];

                            break;

                        //add by wanglulu 20141212  菜单 start
                        case 'nav_wap':
                            if (!isset($source['url_link']) || empty($source['url_link'])) {
                                continue;
                            }
                            if (!isset($source['description']) || empty($source['description'])) {
                                continue;
                            }
                            $content_source->url_link = $source['url_link'];
                            $content_source->description = $source['description'];
                            break;
                        //add by wanglulu 20141212  菜单 end

                        //add by wanglulu 20141212  新品推荐 start
                        case 'flash_wap_new_product':

                            if (!isset($source['url_link']) || empty($source['url_link'])) {
                                continue;
                            }

                            if (!isset($source['img_link']) || empty($source['img_link'])) {
                                continue;
                            }

                            if (!isset($source['description']) || empty($source['description'])) {
                                continue;
                            }

                            $content_source->img_link = $quanliFile->basename_db( $source['img_link'] );
                            $content_source->url_link = $source['url_link'];
                            $content_source->description = $source['description'];

                            break;
                        //add by wanglulu 20141212  新品推荐 end
                        default:
                            break;

                    }
                    

                    $content_source->sort = $key;
                    $content_source->page_type = $args_array['page_type'];
                    $content_source->module = $module_name;
                    $content_source->cityID = $args_array['cityID'];
                    $G_SHOP->DBCA->save($content_source);

                    ++$module_item_amount;

                }

                if ($module_item_amount == 0) {
                    throw new Exception('模块没有内容', 404);
                }

            }

            $G_SHOP->DBCA->commit();

            return array( 'code' => 200, 'message' => '前端模板编辑成功' );

        } catch ( Exception $e ) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else{
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

}